﻿using System;
using System.Linq;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using BestPracticesMVC.BL.Helpers;
using BestPracticesMVC.BL.ViewModels;
using BestPracticesMVC.Data.DataModels;
using BestPracticesMVC.Data.ORM;
using System.Collections.Generic;

namespace BestPracticesMVC.BL
{
    public class HomeBL
    {
        private IUowData DataLayer { get; set; }

        public HomeBL(IUowData dataLyaer) 
        {
            this.DataLayer = dataLyaer;

            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Author, AuthorViewModel>();
            });
        }

        public ICollection<AuthorViewModel> GetAllAuthors()
        {
            var authors = this.DataLayer.Authors
                              .All()
                              .Project()
                              .To<AuthorViewModel>()
            //.Future();  need  EntityFramework.Extensions;
                              .ToList();

            return authors;
        }
  
        public Result CreateAuthor()
        {
            var newAuthor = new Author()
            {
                Id = 6,
                Name = "Jordan",
                NickName = "Gerdan"
            };

            var result = ValidateUser(newAuthor);

            if (result.IsValid)
            {
                this.DataLayer.Authors.Add(newAuthor);
                this.DataLayer.SaveChanges();
            }
           
            return result;
        }
  
        private Result ValidateUser(Author newAuthor)
        {
            var result = new Result();
           
            IsValidAuthorName(newAuthor.Name, result);
            
            return result;
        }

        private void IsValidAuthorName(string name, Result result)
        {
            var ifExist = this.DataLayer.Authors
                              .All()
                              .Where(a => a.Name == name)
                              .Select(a => a.Name)
                              .FirstOrDefault();

            if (ifExist == null)
            {
                result.IsValid = true;
            }
            else
            {
                result.IsValid = false;
                result.Errors.Add("Username is already exist");
            }
        }
    }
}